/** @format */

import { _decorator, Component, Node, v3, Vec3 } from "cc";
import { BaseComponent } from "../../../FrameWork/Module/Component/BaseComponent";
import { gameDataMgr } from "../../_Common/Manager/GameDataManager";
import { MainCamera } from "./MainCamera";
const { ccclass, property } = _decorator;

@ccclass("ParallaxBackground")
export class ParallaxBackground extends BaseComponent {
    @property({ displayName: "视差追随系数" })
    rate: number = 1;

    private _lastPos: Vec3 = v3();
    private _deltaPos: Vec3 = v3();
    private _pos: Vec3 = v3();

    private _bInit: boolean = false;

    private _initPos(): void {
        if (this._bInit) {
            let mainCamera: MainCamera = gameDataMgr.mainCamera;
            if (!mainCamera) {
                return;
            }
            this._pos = this.node.position;
            this._lastPos.x = mainCamera.node.position.x;
            this._lastPos.y = mainCamera.node.position.y;
            this._bInit = true;
        }
    }

    update(deltaTime: number) {
        this._initPos();
        let mainCamera: MainCamera = gameDataMgr.mainCamera;
        this._deltaPos.x = (mainCamera.node.position.x - this._lastPos.x) * this.rate;
        this._deltaPos.y = (mainCamera.node.position.y - this._lastPos.y) * this.rate;

        this._pos.x += this._deltaPos.x;
        this._pos.y += this._deltaPos.y;

        this.node.position = this._pos;

        this._lastPos.x = mainCamera.node.position.x;
        this._lastPos.y = mainCamera.node.position.y;
    }
}
